package com.gjt.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created with Intel IDEA.
 *  基于Udp 的 时间协议
 * @Auther: gjt
 * @Date: 2024/10/27 11:43
 */
public class DayUDPTime {
    private final static int PORT = 13;

    private final static Logger audit = Logger.getLogger("request");
    private final static Logger errors = Logger.getLogger("errors");
    public static void main(String[] args) {

        try(DatagramSocket socket = new DatagramSocket(PORT)){
            while(true){
                try{
                    // 接收 时使用的数据报
                    DatagramPacket request= new DatagramPacket(new byte[1024], 1024);
                    socket.receive(request);

                    // 设置接收缓冲区的大小
                    socket.setReceiveBufferSize(1024);

                    // 获取接收缓冲区的大小
                    socket.getReceiveBufferSize();
                    String daytime = new Date().toString();

                    byte[] bytes = daytime.getBytes("US-ASCII");

                    // 发送时使用的数据报
                    /**
                     *  第一参数表示： 保存数据报数据的字节数组
                     *  第二个参数表示： 该数组中用于数据报数据的字节数
                     */
                    DatagramPacket response = new DatagramPacket(bytes, bytes.length, request.getAddress(), request.getPort());
                    socket.send(response);
                    audit.info(daytime + " " + request.getAddress());
                }catch (IOException ex){
                    errors.log(Level.SEVERE,ex.getMessage(),ex);
                }
            }
        }catch (IOException e){
            errors.log(Level.SEVERE,e.getMessage(),e);
        }
    }
}
